from os import error
from flask import Blueprint,render_template, request,session,redirect
from config import conn,cur,mutex ,r as redis
import datetime

Note = Blueprint('Note',__name__)
 
@Note.route('/',methods=["GET", "POST"])
def index():
    id = session.get('id') 
    name = session.get('name')
    
    return render_template('/Note/index.html',id =id,name=name )

@Note.route('/favouritePage',methods=["GET", "POST"])
def favouritePage():
    id = session.get('id') 
    name = session.get('name')
    return render_template('/note/favourite.html',id =id,name=name )

@Note.route('/querynote',methods=["GET", "POST"])
def querynote():
    data =[]
    cur.execute('select  * from note')
    #print('select  * from note')
    row = cur.fetchone()
    while row:
        #print(row[3] == 1)
        data.append(row)
        row = cur.fetchone()
    
    #print(data)

    return {'message':"success!",'dbdata':data}

@Note.route('/queryfavourite',methods=["GET", "POST"])
def queryfavourite():
    id = session.get('id') 
    cur.execute('select note_id from subscribe where patient_id =' + str(id))
    tempdata =[]
    row = cur.fetchone()
    while row:
        tempdata.append(row)
        row = cur.fetchone()
    
    print(tempdata)
    
    data = []
    for i in range(0,len(tempdata)):
        cur.execute('select * from note where id = ' + str(tempdata[i][0]))
        row = cur.fetchone()
        data.append(row)
    
    # print(data)
    # print(data[0][1])
    return {'message':"success!",'dbdata':data}

@Note.route('/deleteFavourite',methods=["GET", "POST"])
def deleteFavourite():
    id = session.get('id')
    note_id = request.form.get('id')

    cur.execute('delete from subscribe where patient_id = ' + str(id) + 'and note_id = ' + str(note_id))

    return {'message':"success!"}

@Note.route('/addFavourite',methods=["GET", "POST"])
def addFavourite():
    id = session.get('id')
    note_id = request.form.get('id')

    cur.execute('select * from subscribe where patient_id = ' + str(id) + 'and note_id = ' + str(note_id))
    row = cur.fetchone()
    if row :
        return {'message':"failed!"}

    cur.execute('insert into subscribe values('+ str(id) + ',' + str(note_id) + ')')

    return {'message':"success!"}


@Note.route('/logout',methods=["GET", "POST"])
def logout():
    session.clear()
    return {
        'message':"success!"
    }


@Note.before_request
def before():
    if session.get('id') is None:
        return redirect('/Login/',code=301)
    else:
        pass